<template>
  <el-card style="margin-top: 15px;">
    <div slot="header">
      <div style="display: flex;justify-content: space-between;align-items: center">
        <span style="min-width: 64px;margin:0 5px;">
          {{`${linkFrom}关联${linkTo}信息配置`}}
        </span>
        <!--        <el-button-->
        <!--          :hide-on-click="false"-->
        <!--          @click="saveProductLink" type="success">保存配置-->
        <!--        </el-button>-->
      </div>
    </div>

    <!--         :button-texts="[ '移除','添加',]"
     -->
<!--    <el-row :gutter="globalGutter">-->
      <!--  产品基本信息,内部包含了修改,因为修改的逻辑是通用的,实在是不同的在外面传给内部组件  -->
<!--      <el-col :span="24">-->
        <!--        <azure/>-->
<!--        <el-alert-->
<!--          :closable="false"-->
<!--          :title="`左侧为全部${linkTo},右侧为已经配置过的${linkTo},目前搜索还未完善,请不要使用`"-->
<!--          effect="dark"-->
<!--          show-icon-->
<!--          style="margin-bottom: 15px;"-->
<!--          type="info"-->
<!--        />-->

        <!--

       -->
        <el-transfer
          :data="data"
          :filter-method="filterMethod"
          :props="{
            key: 'ProductId',
            label: 'ProductName'
          }"
          :titles="['全部组件', '已配置组件']"
          class="azure-transfer"
          filter-placeholder="输入组件名搜索"
          filterable
          ref="transfer"
          style="display: flex;align-items: center;justify-content: center;"
          target-order="push"
          v-model="checkedIds">

          <el-button @click="saveProductLink" size="mini"
                     slot="right-footer" style="margin-left: 10px;" type="success">
            保存关系配置
          </el-button>

          <!--          <el-button-->
          <!--            @click="saveProductLink"-->
          <!--            size="mini" type="primary">保存关系配置-->
          <!--          </el-button>-->
        </el-transfer>
<!--      </el-col>-->

      <!--      <el-card style="margin-top: 15px;" >-->
      <!--        <div slot="header">-->
      <!--          <div style="display: flex;justify-content: space-between;align-items: center">-->
      <!--            <span style="min-width: 64px;margin:0 5px;"></span>-->
      <!--&lt;!&ndash;            <el-button&ndash;&gt;-->
      <!--&lt;!&ndash;              :hide-on-click="false"&ndash;&gt;-->
      <!--&lt;!&ndash;              @click="saveProductLink" type="primary">保存配置&ndash;&gt;-->
      <!--&lt;!&ndash;            </el-button>&ndash;&gt;-->
      <!--          </div>-->
      <!--        </div>-->
      <!--      </el-card>-->
<!--      <el-col :span="8" style="min-height: 420px;">-->

<!--        <el-card-->
<!--          :body-style="{ padding: '0px' }"-->
<!--          style="max-height: 100%"-->
<!--        >-->
<!--          <el-image-->
<!--            :preview-src-list="Array.of(img)"-->
<!--            :src="img"-->
<!--            fit="cover"-->
<!--          />-->
<!--          <div style="padding: 14px;">-->
<!--            <span>好吃的Friday</span>-->
<!--            <div>-->
<!--              <time class="time">{{ new Date() }}</time>-->
<!--            </div>-->
<!--          </div>-->
<!--        </el-card>-->


<!--        <el-button-->
<!--          icon="el-icon-search"-->
<!--          round-->
<!--          size="mini"-->
<!--          slot="reference"-->
<!--          type="primary">按条件搜索{{linkTo}}-->
<!--        </el-button>-->

<!--      </el-col>-->

<!--    </el-row>-->
    <el-row :gutter="globalGutter">

      <azure-dynamic-table
        :column-des-objs="columnDesObjs"
        :data="hasRelateList"
        :empty-text="`该暂${linkFrom}暂无配置的${linkTo} 🎉🎉🎉🎉🎉`"
      >
        <template slot="tableHead">
          <el-alert
            :closable="false"
            :title="`点击${linkTo}名既可进入到编辑页面`"
            effect="dark"
            show-icon
            type="success"
          />

          <!--          <el-button-->
          <!--            :hide-on-click="false"-->
          <!--            @click="saveProductLink"-->
          <!--            size="mini" type="primary">保存关系配置-->
          <!--          </el-button>-->
          <!--            <AButton @click="handleConfigRelate" type="success">-->
          <!--              {{`配置当前${linkFrom}的${linkTo}`}}-->
          <!--            </AButton>-->
          <!--        <AButton @click="saveRelate2Server" type="primary">-->
          <!--          {{`保存${linkFrom}与所属${linkTo}`}}-->
          <!--        </AButton>-->
          <!--          <el-input clearable placeholder="请输入内容"-->
          <!--                    style="width: 200px;margin-right: 20px" suffix-icon="el-icon-search"-->
          <!--                    v-model="searchKey"/>-->
          <!--        <ASelect :options="PRODUCT_SYNC_STATUS" :value.sync="putAway" placeholder="选择产品同步状态"/>-->
        </template>
        <!--        <template slot="quantity3" slot-scope="{scope:{row,$index}}">-->
        <!--          <div>{{row.quantity+'个'}}</div>-->
        <!--        </template>-->

        <template slot="quantity3" slot-scope="{scope:{row,$index}}">
          <div v-if="!row.isEdit">
            {{`${row.quantity }个`}}
          </div>
          <el-input-number
            :max="99"
            :min="1"
            size="mini"
            v-else v-model="row.quantity">
          </el-input-number>
        </template>

        <template slot="ProductName" slot-scope="{scope:{row,$index}}">
          <!--          <el-button-->
          <!--            @click="handleEdit({row,$index})"-->
          <!--            type="text"> {{row.ProductName}}</el-button>-->

          <el-button
            @click="handleEdit({row,$index})"
            size="mini" type="success">
            {{ row.ProductName }}
          </el-button>
        </template>


        <template slot="operator" slot-scope="{scope:{row,$index}}">
          <!--          <AButton-->
          <!--            style="margin-right: 5px;"-->
          <!--            @click="handleEdit({row,$index})" type="primary">{{linkTo}}详细</AButton>-->

          <a-inline-edit :edit-form-data="row"
                         :is-edit-flag.sync="row.isEdit"
                         :submit-next="handleEditProduct"/>
          <!--          <el-popconfirm-->
          <!--            :title="`是否确定删除该${linkFrom}关联的${linkTo}？`"-->
          <!--            @onConfirm="handleDeleteProductRelate({row,$index})"-->
          <!--            style="margin-left: 10px;"-->
          <!--            v-show="!row.isEdit">-->
          <!--            <AButton icon="el-icon-delete" slot="reference" type="info">-->
          <!--              删除-->
          <!--            </AButton>-->
          <!--          </el-popconfirm>-->

        </template>

      </azure-dynamic-table>
    </el-row>
  </el-card>

</template>

<script>
  import { deepClone } from '@/utils'
  import { ModifyProductComponent, ModifyProductMaterial, PageQueryProduct } from '@/api/productInformation'
  import { productTypesEnum } from '@/enums/product'
  import productMixin from '@/views/baseproduct/components/product/productMixin'
  import { ERR_OK } from '@/utils/commons'
  import { debugLogger } from '@/utils/fridayClub/functianal'
  import { dataStatusTypesEnum } from '@/enums/common'
  import { objFirstKeyLowerCase } from '@/utils/fridayClub/objectUtil'
  import layoutMixin from '@/mixins/layoutMixin'
  import AButton from '@/components/ATheFridayClub/AButton'
  import AzureDynamicTable from '@/components/ATheFridayClub/mDynamicTable/AzureDynamicTable'
  import { productBaseCols } from '@/views/baseproduct/mixins/productUtil'
  import AInlineEdit from '@/components/ATheFridayClub/inlineEdit/AInlineEdit'
  import ProductCategoricalSelect from '@/components/ATheFridayClub/businessSelect/product/productCategoricalSelect'
  import ProductPrintType from '@/components/ATheFridayClub/businessSelect/print/productPrintType'
  import ShopTypeSelect from '@/components/ATheFridayClub/businessSelect/product/shopTypeSelect'
  import ShowMore from '@/components/ATheFridayClub/ShowMore'
  import Azure from '@/views/baseproduct/components/product/azure'

  const columnDesObjs = Array.of(
    ...productBaseCols,
    { key: 'quantity3', label: '数量' },
    { key: 'operator', label: '操作', width: '170' }
  )

  const img = require('../../imgs/1920x1080_25_04_2020_2.jpg')
  export default {
    name: 'ProductRelateConfigTransfer',
    components: {
      Azure,
      ShowMore,
      ShopTypeSelect,
      ProductPrintType,
      ProductCategoricalSelect,
      AInlineEdit,
      AzureDynamicTable,
      AButton
    },
    props: {
      hasRelateList: {
        type: Array,
        default: () => (Array.of())
      },
      modifyData: { //  因为修改配置信息要用
        type: Object,
        default: () => ({})
      }
    },
    mixins: [productMixin, layoutMixin],
    data() {
      return {
        img,
        data: Array.of(), //  全部数据
        // data: generateData(),
        // checkedItems: [],
        checkedIds: [],  //  最后的结果

        // originItems: [], //  原始的
        originIds: [],
        columnDesObjs,

        searchFormData: {
          name: '', //  产品名

          code: '',//  产品编码
          productType: null,  //  el-select 匹配不到会显示一个奇怪的值,必须为null

          categoricalId: '',
          printTypeId: '',
          shopType: '',
          status: dataStatusTypesEnum['正常'],  //  默认传正常,不需要删除的

          page: 1,
          limit: 10

        },
        queryKey: new Date().getTime(),
        searchData: []
      }
    },
    async created() {
      //  get all data
      //  ProductId

      const uw = this.$watch('modifyData', (newValue) => {
        this.getData()
        uw()
      })

      //  set Now Checked
      const unWatchCall = this.$watch('hasRelateList', (newValue) => {
        // this.checkedIds = newValue.map(v => v.ProductId)
        this.checkedIds = newValue.map(v => v.partId)
        this.originIds = [...this.checkedIds]
        this.checkedItems = deepClone(newValue)   //  暂时不会被修改
        this.originItems = deepClone(newValue)  //  原始的
      }, { immediate: true })

      //  拼装数据和分类

      // this.checkedIds.map((item) => {
      //   const {} = item
      // })
      await this.$nextTick()
      // window.ccc = this.$refs['transfer'].$children[0]

      window.lp = this.$refs['transfer'].$refs['leftPanel']

    },
    watch: {
      searchFormData: {
        deep: true,
        handler(val) {
          this._emitQuery()
        }
      }
    },
    methods: {

      hiddenFilterInput() {

      },
      //  改变搜索关键字,左侧的 transfer panel
      async _emitQuery() {
        // window.ccc = this.$refs['transfer'].$children

        //  右侧不执行方法
        this.$refs['transfer'].$refs['rightPanel']['filterMethod'] = function() {
          return true
        }

        // this.$refs['transfer'].$children[0]['query'] = ++this.queryKey
        this.$refs['transfer'].$refs['leftPanel'].query = ++this.queryKey
        // await this.$nextTick()

      },
      filterMethod(query, item) {
        // return item.pinyin.indexOf(query) > -1;
        // console.log(item)
        // const { ProductId } = item
        // checkableData
        // console.log('filterMethod trigger');

        // const showItemIds = this.searchData.map(v => v.ProductId)

        // return true | false

        //  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        // if (this.searchData.length === 0) {
        //   return true
        // }
        // const showItemCodes = this.searchData.map(v => v.Code)
        // return showItemCodes.includes(item.Code)
        //  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        // key: 'ProductId',
        //   label: 'ProductName'
        const label = item['ProductName'].toString()
        // console.log(label);
        return label.toLowerCase().indexOf(query.toLowerCase().trim()) > -1
        // return true
      },

      //  搜索数据
      async reGetData() {
        // this.initAllProductListTable()
        // this.searchData =  this.getData({ notSet: true })
        this.searchData = await this.getData({ notSet: true })  //  获取新的数据

        this._emitQuery() //  触发 transfer 的 query > filterMethod

      },
      resetSearch() {
        this.resetForm('searchDataForm')
        // this.initAllProductListTable() //  不需要分页
        this.searchData = this.getData({ notSet: true })

      },
      initAllProductListTable() {
        this.searchFormData.page = 1
        // this.allProductTableData = Array.of()
        // this.infiniteId++
      },

      //  组件不能新增只能修改
      handleEdit({ row, $index }) {
        //  disable : if不为组件不能编辑
        //  跳转页面,组件详细
        const { ProductId, Code } = row
        // this.jump2ModifyProduct({ ProductId, Code })
        this.$router.push({ name: 'componentModify', query: { ProductId, Code } })
      },

      async handleDeleteProductRelate({ row, $index } = {}) {
        try {

          const { componentId, partId, productId, quantity } = row

          const { Code, Result } = await ModifyProductComponent(Array.of({
            componentId, partId, productId, quantity, status: dataStatusTypesEnum['删除']
          }))
          if (Code === ERR_OK) {
            row.status = dataStatusTypesEnum['删除']
            const { [$index]: deleteItem, ...other } = this.hasRelateList
            console.log(Object.values(other))

            this.$emit('update:hasRelateList', Object.values(other))
            this.$message.success(`删除${this.linkFrom}下的${this.linkTo}关联成功`)
          } else {
            this.$message.warning(`删除${this.linkFrom}下的${this.linkTo}关联失败`)
          }
        } catch (e) {
          console.log(e)
        }
      },
      async handleEditProduct({ row, resolve, reject } = {}) {
        try {
          // const isSuc = await this.ModifyProductMaterial({ dataList: Array.of(row) })
          const { Code, Result } = await ModifyProductComponent(Array.of(row))
          if (Code === ERR_OK) {
            resolve()
            this.$message.success(`保存${this.linkFrom}下的${this.linkTo}数量成功`)
          } else {
            reject()
            this.$message.warning(`保存${this.linkFrom}下的${this.linkTo}数量失败`)
          }
        } catch (e) {
          console.log(e)
          reject()
        }
      },

      async sync2Server(dataList) {
        const genOrderByIdx = (list) => list.map((v, i) => ({
          ...v, orderIndex: i
        }))

        try {
          const { Code } = await ModifyProductComponent(dataList |> genOrderByIdx)
          if (Code === ERR_OK) {
            this.$message.success(`配置${this.linkFrom}的${this.linkTo}成功`)
          } else {
            this.$message.warning(`配置${this.linkFrom}的${this.linkTo}失败`)
          }
        } catch (e) {
          console.log(e)
        }
      },
      async saveProductLink() {
        //  查出全部的应该是从 componentId 中取
        //  当前已有的是从 partId 取出
        const deleteIds = this.originIds.filter(id => !this.checkedIds.includes(id))
        // |> debugLogger('deleteIds')
        const insertIds = this.checkedIds.filter(id => !this.originIds.includes(id))
        // |> debugLogger('insertIds ')
        // const doi = [...deleteIds, ...insertIds]
        const updateIds = this.checkedIds.filter(id => this.originIds.includes(id))
        // |> debugLogger('updateIds ')
        const paramsFactory = ({ componentId, partId, productId, quantity, status } = {}) => {
          return {
            componentId,
            partId,
            productId,
            quantity,
            status
          }
        }

        //  delete 和 update 取原有的 , insert 取新的
        const deleteItems = this.hasRelateList.filter(v => deleteIds.includes(v.partId))
          .map(({ partId, productId, quantity, componentId }) =>
            paramsFactory({
              partId, productId, quantity, componentId,
              status: dataStatusTypesEnum['删除']
            }))
          |> debugLogger('deleteItems po ')

        const { ProductId } = this.modifyData

        const insertItems = (this.data.filter(v => insertIds.includes(v.ProductId))
          |> objFirstKeyLowerCase)::Array.prototype.map(({ productId: partId }) =>
          paramsFactory({
            productId: ProductId, partId, quantity: 1,
            status: dataStatusTypesEnum['正常']
          }))
          |> debugLogger('insertItems po')

        const updateItems = this.hasRelateList.filter(v => updateIds.includes(v.partId))
          .map(({ partId, productId, quantity, componentId, status }) =>
            paramsFactory({ partId, productId, quantity, componentId, status }))
          |> debugLogger('updateItems po')

        await this.sync2Server([...deleteItems, ...insertItems, ...updateItems])
        // checkedIds
        // this.originIds.filter(v=> !this.checkedIds.includes(v))
        this.$emit('refreshData', { deleteIds })

        // tableDataUpdate
        //  修改以左边为准?????
        // this.hasRelateList.reduce((acc, cur) => {
        //   const { partId } = cur
        //   const changePropName = (() => {
        //     if (insertIds.includes(partId)){
        //       return 'insertItemList'
        //     } else if(updateIds.includes(partId)){
        //       return 'updateItemList'
        //     } else if(deleteIds.includes(partId)){
        //       return 'deleteItemList'
        //     }else{
        //       return 'rest'
        //     }
        //   })()
        //   return {
        //     ...acc,[changePropName]:[...acc[changePropName],cur]
        //   }
        // }, {
        //   insertItemList: Array.of(),
        //   updateItemList: Array.of(),
        //   deleteItemList: Array.of()
        // }) |> debugLogger()

        //  外部删除掉这些ids
        // this.$emit('update:hasRelateList')

      },

      async getData({ notSet } = {}) {
        const { Code, Result } = await PageQueryProduct({
          ...this.searchFormData,
          // productType: productTypesEnum.getProp(this.proxyProductType, 'config2MappingValue'),
          pageSize: 100, pageNum: 1,
          productType: productTypesEnum.getProp(this.proxyProductType, 'config2MappingValue') ?? 0,
          status: -1 //  查询全部
          //  其他的查询项
          // name, code, categoricalId, printTypeId, shopType, status
        })
        if (Code === ERR_OK) {
          const { CurrentPage, RecordCount, Rows } = Result
          if (!notSet) {
            this.data = Rows
          }
          return Rows
        }
        return []
      }

    }

  }
</script>

<style lang="scss" scoped>

  .azure-transfer {
    /deep/ .el-transfer-panel {
      width: 35vw;
    }
  }

</style>
